package com.hou.hpsj_springboot.service.Impl;

import com.hou.hpsj_springboot.bean.Users;
import com.hou.hpsj_springboot.entity.R;

import com.hou.hpsj_springboot.mapper.LoginMapper;
import com.hou.hpsj_springboot.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import java.io.UnsupportedEncodingException;


@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    LoginMapper LoginMapper;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private ServletContext servletContext;


    @Override
    public R getCaptcha(String email) throws MessagingException, UnsupportedEncodingException {
        log.info("正在向{}发送验证码...", email);
        //生产验证码
        int captcha = (int) (Math.random() * 10000 + 900000);
        log.info("验证码：{}", captcha);
        //保存验证码
        servletContext.setAttribute(email, captcha);
        //TODO:实现发送邮件
        // 创建一个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();
        // 创建 MimeMessageHelper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        // 发件人邮箱和名称
        helper.setFrom("tengyue5143@163.com", "抖音");
        // 收件人邮箱
        helper.setTo(email);
        // 邮件标题
        helper.setSubject("抖音-验证码");
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(captcha + "", true);

        // 发送
       javaMailSender.send(message);
        log.info("验证码已发送");
        log.info("验证码：{}", captcha);
        return R.ok("验证码已发送");
    }

    @Override
    public void registerOrLogin(  Users user) {
        Users user1 = LoginMapper.selectUserByEmail(user.getEmail());
        if(user1==null){
            LoginMapper.insert(user);
        }
        String captcha = servletContext.getAttribute(user.getEmail()).toString();
        if(!captcha.equals(user.getPasswordhash())){
            throw new RuntimeException("验证码错误");
        }

    }


}
